package com.cropdoctor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.CommentMapper;
import com.cropdoctor.mapper.PostMapper;
import com.cropdoctor.mapper.PublishCourseMapper;
import com.cropdoctor.model.dto.PostDto;
import com.cropdoctor.model.po.CommentPo;
import com.cropdoctor.model.po.PostPo;
import com.cropdoctor.model.po.PublishCoursePo;
import com.cropdoctor.model.vo.CommentVO;
import com.cropdoctor.model.vo.PublishCourseInfoVO;
import com.cropdoctor.service.CommentService;
import com.cropdoctor.util.ContextGet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentMapper commentMapper;

    @Autowired
    PostMapper postMapper;

    @Autowired
    PublishCourseMapper publishCourseMapper;

    @Autowired
    RedisTemplate redisTemplate;
    final static String POST_LIKE_KEY = "post_like_";

    @Override
    @Transactional
    public Result<Long> createComment(CommentPo commentPo) {
        //向评论表中插入数据
        int result = commentMapper.insert(commentPo);
        if (result <= 0) throw new CustomException("评论添加失败！");
        return Result.success(commentPo.getId());
    }

    @Override
    @Transactional
    public Result<String> userDeleteComment(long idComment) {
        //获取该条评论发布者的id
        CommentPo commentPo = commentMapper.selectById(idComment);
        long commenterId = commentPo.getCommenterId();

//        if (ContextGet.getUserId() != commenterId) throw new CustomException("只能删除自己发布的评论！");

        //删除的时候需要将回复该评论的评论及其子评论一起删除
        //构造删除条件
        LambdaQueryWrapper<CommentPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommentPo::getSuperiorId,idComment);//子评论
        wrapper.eq(CommentPo::getReviewedId,idComment);//回复该评论的评论
        int result1 = commentMapper.deleteById(idComment);//删除该评论
        List<CommentPo> children = commentMapper.selectList(wrapper);
        if(children.size() != 0){//如果有子评论
            int result = commentMapper.delete(wrapper);
            if(result <= 0) throw new CustomException("评论删除失败！");
        }

        //若删除异常，则抛出CustomException异常
        if (result1 <= 0) throw new CustomException("评论删除失败！");

        return Result.success("评论删除成功！");
    }

    @Override
    public Result<PostDto> getPostWithAllComment(long idPost) {
        //构造查询条件
        PostDto postDto = postMapper.selectPostInfo(idPost);
        if(postDto == null) throw new CustomException("该帖子不存在!");

        //查询该帖子下的所有评论
        List<CommentVO> commentPos = commentMapper.selectPostListWithUser(idPost);
        Long userId = ContextGet.getUserId();
        String key = POST_LIKE_KEY+idPost;
        postDto.setLike(redisTemplate.opsForSet().isMember(key,userId.toString()));

        postDto.setComments(commentPos);
        return Result.success(postDto);
    }

    @Override
    public Result<CommentPo> getComment(long idComment) {
        CommentPo commentPo = commentMapper.selectById(idComment);

        if (commentPo == null) throw new CustomException("查询失败！该条评论不存在！");

        return Result.success(commentPo);
    }

    @Override
    public Result<String> likeComment(long idComment) {
        //通过评论id，从帖子表中查询对应的评论信息
        CommentPo commentPo = commentMapper.selectById(idComment);

        //若查询异常，则抛出CustomException异常
        if (commentPo == null) throw new CustomException("查询失败！无相应评论");
        int likeNumber = commentPo.getLikeNumber();
        commentPo.setLikeNumber(++likeNumber);

        int result = commentMapper.updateById(commentPo);
        //若更新异常，则抛出CustomException异常
        if (result <= 0) throw new CustomException("数据更新失败！");
        return Result.success("更新成功！");
    }



    @Override
    public Result<String> adminDeleteComment(long idComment) {
        //构造删除条件
        LambdaQueryWrapper<CommentPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommentPo::getSuperiorId,idComment);
        int result1 = commentMapper.deleteById(idComment);
        int result2 = commentMapper.delete(wrapper);
        //若删除异常，则抛出CustomException异常
        if (result1 <= 0 && result2<= 0 ) throw new CustomException("评论删除失败！");

        return Result.success("评论删除成功！");
    }

    @Override
    public Result<PublishCourseInfoVO> getCourseWithAllComment(long idCourse) {
        //构造查询条件
        PublishCourseInfoVO publishCourseInfoVO = publishCourseMapper.selectWithUserAndVideo(idCourse);
        if(publishCourseInfoVO == null) throw new CustomException("该帖子不存在!");

        List<CommentVO> commentVOS = commentMapper.selectCourseListWithUser(idCourse);

        publishCourseInfoVO.setComments(commentVOS);
        return Result.success(publishCourseInfoVO);
    }
}
